﻿using System;
using System.Collections.Generic;
using System.Linq;
using ComponentFactory.Krypton.Toolkit;
using System.Data;

namespace TestApi
{
    /// <summary>
    /// 
    /// </summary>
    public partial class TextForm : KryptonForm
    {
        /// <summary>
        /// 
        /// </summary>
        public TextForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="content"></param>
        public TextForm(string content)
            : this()
        {
            _contentTextBox.Text = content;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="content"></param>
        public TextForm(LogViewItem item)
            : this()
        {
            var dt = new DataTable();
            dt.Columns.Add(new DataColumn("order"));
            dt.Columns.Add(new DataColumn("key"));
            dt.Columns.Add(new DataColumn("content"));
            _headersGridView.AutoGenerateColumns = false;
            _headersGridView.DataSource = dt;

            _contentTextBox.Text = item.Content;
            Array.ForEach(item.Headers.AllKeys, key =>
            {
                var dr = dt.NewRow();
                dr["order"] = (dt.Rows.Count + 1).ToString();
                dr["key"] = key;
                dr["content"] = item.Headers[key];
                dt.Rows.Add(dr);
            });

            var nameValuePairs = item.PostData != null ? item.PostData.Split(new char[] { '&' },
                StringSplitOptions.RemoveEmptyEntries) : new string[] { };
            Array.ForEach(nameValuePairs, nameValuePair =>
            {
                var nameValuePairParts = nameValuePair.Split(new char[] { '=' },
                    StringSplitOptions.RemoveEmptyEntries);
                if (nameValuePairParts.Length == 2)
                {
                    var dr = dt.NewRow();
                    dr["order"] = (dt.Rows.Count + 1).ToString();
                    dr["key"] = nameValuePairParts[0];
                    dr["content"] = nameValuePairParts[1];
                    dt.Rows.Add(dr);
                }
                else if (nameValuePairParts.Length == 1)
                {
                    var dr = dt.NewRow();
                    dr["order"] = (dt.Rows.Count + 1).ToString();
                    dr["key"] = nameValuePairParts[0];
                    dt.Rows.Add(dr);
                }
            });
        }
    }
}
